package com.webSite.demo.cy.controller;

import java.io.IOException;
import java.util.Date;
import java.util.List;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.boot.autoconfigure.EnableAutoConfiguration;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.multipart.MultipartFile;

import com.webSite.demo.cy.bean.HomeNews;
import com.webSite.demo.cy.mapper.HomeNewsMapper;
import com.webSite.demo.cy.utils.FileUtils;
import com.webSite.demo.cy.utils.PageUtils;

import cn.hutool.core.util.PageUtil;


@Controller
@EnableAutoConfiguration
public class HomeNewsController {

	@Autowired
	HomeNewsMapper homeNewsMapper;
	
	@RequestMapping("/homeNews.html")
    String homeNews(Model model,@RequestParam(value="index",defaultValue="0")int index) {
		List<HomeNews> list = homeNewsMapper.findAllInfo();
		
		List<HomeNews> newList = homeNewsMapper.findAllPage(index*5);
		int totalPage = PageUtil.totalPage(list.size()+1, 5);//总页数
		//参数意义分别为：当前页、总页数、每屏展示的页数
		int[] rainbow = PageUtil.rainbow(index*5, totalPage, 5);
		PageUtils pageUtil = new PageUtils(totalPage,rainbow,index+1);
		if(!newList.isEmpty()) {
			model.addAttribute("pageUtil", pageUtil);
			model.addAttribute("newList", newList);
			
		}
        return "admin/homeNews";  
    }
	
	@RequestMapping("/addHomeNews.html")
	public String addHomeNews(HomeNews homeNews,MultipartFile uploadFile) {
		homeNews.setCreated(new Date());
		homeNews.setUpdated(new Date());
		homeNews.setState(1);
		if(uploadFile!=null) {
			FileUtils fileUtils =new FileUtils();
			try {
				fileUtils.uploadToInputStream(uploadFile.getOriginalFilename(), uploadFile.getInputStream());
				homeNews.setImage(uploadFile.getOriginalFilename());
			} catch (IOException e) {
				homeNews.setImage("");
				e.printStackTrace();
			}
		}
		homeNewsMapper.insertHomeNews(homeNews);
		return "redirect:/homeNews.html";
	}
	
	@RequestMapping("/updateNews.html")
    String JhomeNews(int id,Model model) {
		HomeNews homeNews = homeNewsMapper.findOne(id);
		model.addAttribute("homeNews", homeNews);
        return "admin/update/updateNews"; 
    }
	
	@RequestMapping("/updateHomeNews.html")
    String updateHomeNews(HomeNews homeNews) {
		homeNews.setUpdated(new Date());
		homeNewsMapper.updateHomeNews(homeNews);
		return "redirect:/homeNews.html";
    }
	
	@RequestMapping("/deleteNews.html")
    String deleteNews(int id) {
		homeNewsMapper.updateState(id);
		return "redirect:/homeNews.html";
    }
}
